package bb.lanxing.lib.devices.bryton.bbcp;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.core.view.InputDeviceCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
//import com.alipay.sdk.util.e;
//import com.efs.sdk.base.core.util.NetworkUtil;
import bb.lanxing.lib.devices.bryton.nordic.dfu.AbortedException;
import bb.lanxing.lib.devices.bryton.nordic.dfu.DeviceDisconnectedException;
import java.lang.reflect.Method;

@SuppressLint("MissingPermission")
public abstract class BleManager {
    public static final int BBCP_SUCCESS = 0;
    public static final int ERROR_ABORTED = 263;
    public static final int ERROR_BBCP_PACKET_INVALID = 264;
    public static final int ERROR_BBCP_RESPONSE_INVALID = 271;
    public static final int ERROR_BLUETOOTH = 272;
    public static final int ERROR_CONNECTION_MASK = 1024;
    public static final int ERROR_DATA_CRC = 275;
    public static final int ERROR_DATA_INVALID = 265;
    public static final int ERROR_DATA_LOSS = 266;
    public static final int ERROR_DATA_TIMEOUT = 273;
    public static final int ERROR_DEVICE_BUSY = 270;
    public static final int ERROR_DEVICE_DISCONNECTED = 256;
    public static final int ERROR_DEVICE_NOT_BONDED = 269;
    public static final int ERROR_EXCEPTION = 276;
    public static final int ERROR_FILE_CLOSED = 258;
    public static final int ERROR_FILE_INVALID = 259;
    public static final int ERROR_FILE_IO_EXCEPTION = 260;
    public static final int ERROR_FILE_NOT_FOUND = 257;
    public static final int ERROR_MASK = 256;
    public static final int ERROR_REMOTE_MASK = 512;
    public static final int ERROR_RESPONSE_DEVICE_INFO = 274;
    public static final int ERROR_SERVICE_DISCOVERY_NOT_STARTED = 261;
    public static final int ERROR_SERVICE_NOT_SUPPORT = 267;
    public static final int ERROR_UNSUPPORTED_DEVICE = 262;
    public static final int ERROR_USER_ADDRESS_INVALID = 268;
    protected static final String EXTRA_DATA = "com.brytonsport.bbcp.EXTRA_DATA";
    protected static final String EXTRA_TARGET = "com.brytonsport.bbcp.EXTRA_TARGET";
    public static final int STATE_CONNECTED = -2;
    public static final int STATE_CONNECTED_AND_READY = -3;
    public static final int STATE_CONNECTING = -1;
    public static final int STATE_DISCONNECTED = 0;
    public static final int STATE_DISCONNECTING = -4;
    protected String TAG;
    protected boolean mAborted;
    protected volatile Handler mAsyncHandler;
    protected volatile Looper mAsyncLooper;
    protected BluetoothGatt mBluetoothGatt;
    protected volatile int mConnectionState;
    protected Context mContext;
    protected int mErrorState;
    protected final Object mLock = new Object();
    private final int CONNECT_TIMEOUT_MS = 5000;
    private volatile boolean mNotified = false;

    public void _connect(Context context, BluetoothDevice bluetoothDevice, BluetoothGattCallback bluetoothGattCallback, BroadcastReceiver broadcastReceiver) throws AbortedException, DeviceDisconnectedException {
        if (this.mConnectionState == -1) {
            logi("Connection error: during connecting");
            this.mErrorState = InputDeviceCompat.SOURCE_GAMEPAD;
            return;
        }
        this.mAborted = false;
        this.mErrorState = 0;
        this.mConnectionState = -1;
        this.mContext = context;
        logi("Connecting to the device...");
        BluetoothGatt connectGatt = bluetoothDevice.connectGatt(context, false, bluetoothGattCallback);
        this.mBluetoothGatt = connectGatt;
        if (connectGatt == null) {
            this.mErrorState = 272;
            loge("return null gatt");
            throw new DeviceDisconnectedException("return null gatt", this.mConnectionState);
        }
        try {
            synchronized (this.mLock) {
                while (true) {
                    if ((this.mConnectionState != -1 && this.mConnectionState != -2) || this.mErrorState != 0 || this.mAborted) {
                        break;
                    }
                    this.mNotified = false;
                    this.mLock.wait(5000L);
                    if (!this.mNotified) {
                        loge("connect timeout");
                        break;
                    }
                }
            }
        } catch (InterruptedException e) {
            loge("Sleeping interrupted", e);
        }
        if (this.mErrorState > 0) {
            loge("An error occurred while connecting to the device");
            throw new DeviceDisconnectedException("An error occurred while connecting to the device", this.mConnectionState);
        } else if (this.mAborted) {
            logi("connect aborted");
            this.mErrorState = 263;
            throw new AbortedException();
        } else if (this.mNotified) {
        } else {
            this.mErrorState = 273;
            throw new DeviceDisconnectedException("An error occurred while connecting to the device", this.mConnectionState);
        }
    }

    public void _handleConnectionStateChange(final BluetoothGatt bluetoothGatt, int i, int i2) {
        if (this.mErrorState != 0 && this.mConnectionState == -1) {
            this.mConnectionState = 0;
            return;
        }
        if (i != 0) {
            loge("Connection state change error: " + i + " newState: " + i2);
            this.mErrorState = i | 1024;
        } else if (i2 == 2) {
            logi("Connected to GATT server");
            this.mConnectionState = -2;
            this.mAsyncHandler.post(new Runnable() {
                @Override
                public void run() {
                    boolean discoverServices = bluetoothGatt.discoverServices();
                    BleManager bleManager = BleManager.this;
                    StringBuilder sb = new StringBuilder();
                    sb.append("Attempting to start service discovery...");
                    sb.append(discoverServices ? "succeed" : "failed"/*e.b*/);
                    bleManager.logi(sb.toString());
                    if (!discoverServices) {
                        BleManager.this.loge("discover services failed");
                        BleManager.this.mErrorState = 261;
                    }
                }
            });
        } else if (i2 == 0) {
            logi("Disconnected from GATT server");
            if (this.mConnectionState != -4) {
                logi("Disconnected from remote device");
                BluetoothGatt bluetoothGatt2 = this.mBluetoothGatt;
                if (bluetoothGatt2 != null) {
                    bluetoothGatt2.disconnect();
                }
            }
            this.mConnectionState = 0;
        }
        synchronized (this.mLock) {
            logi("ConnectionStateChange: notify all");
            this.mNotified = true;
            this.mLock.notifyAll();
        }
    }

    public void _handleServicesDiscovered(BluetoothGatt bluetoothGatt, int i) {
        if (i == 0) {
            logi("Services discovered");
            this.mConnectionState = -3;
        } else {
            loge("Service discovery error: " + i);
            this.mErrorState = i | 1024;
        }
        synchronized (this.mLock) {
            this.mNotified = true;
            this.mLock.notifyAll();
        }
    }

    public void disconnect() {
        logi("connection state=" + this.mConnectionState);
        if (this.mConnectionState == -1) {
            return;
        }
        if (this.mConnectionState == -2 || this.mConnectionState == -3) {
            this.mErrorState = 0;
            this.mConnectionState = -4;
            if (this.mBluetoothGatt != null) {
                logi("Disconnecting from the device...");
                this.mBluetoothGatt.disconnect();
                waitUntilDisconnected(2);
                closeBluetoothGatt();
                this.mConnectionState = 0;
            }
        }
//        logi(NetworkUtil.NETWORK_CLASS_DISCONNECTED);
    }

    public void closeBluetoothGatt() {
        if (this.mConnectionState == -1) {
            return;
        }
        logi("Cleaning up...");
        BluetoothGatt bluetoothGatt = this.mBluetoothGatt;
        if (bluetoothGatt == null) {
            return;
        }
        bluetoothGatt.close();
        this.mBluetoothGatt = null;
    }

    public void waitUntilDisconnected(int i) {
        try {
            synchronized (this.mLock) {
                while (this.mConnectionState != 0 && this.mErrorState == 0 && !this.mAborted && i > 0) {
                    this.mLock.wait(2000L);
                    if (i > 0) {
                        i--;
                    }
                    logi(String.format("wake: connectionState=%d, error=%d,mAborted=%b, waitCount=%d", this.mConnectionState, this.mErrorState, this.mAborted, i));
                }
                logi(String.format("leave: connectionState=%d, error=%d,mAborted=%b, waitCount=%d", this.mConnectionState, this.mErrorState, this.mAborted, i));
            }
        } catch (InterruptedException e) {
            loge("Sleeping interrupted", e);
        }
    }

    public void refreshDeviceCache(BluetoothGatt bluetoothGatt) {
        try {
            Method method = bluetoothGatt.getClass().getMethod("refresh");
            if (method == null) {
                return;
            }
            boolean booleanValue = (Boolean) method.invoke(bluetoothGatt, new Object[0]);
            logi("Refreshing result: " + booleanValue);
        } catch (Exception e) {
            loge("An exception occured while refreshing device", e);
        }
    }

    public void sendProgressBroadcast(int i, String str) {
        Intent intent = new Intent(str);
        intent.putExtra(EXTRA_DATA, i);
        LocalBroadcastManager.getInstance(this.mContext).sendBroadcast(intent);
    }

    public void sendResultBroadcast(int i, String str) {
        Intent intent = new Intent(str);
        intent.putExtra(EXTRA_DATA, i);
        LocalBroadcastManager.getInstance(this.mContext).sendBroadcast(intent);
    }

    public void loge(String str) {
        Log.e(this.TAG, str);
    }

    public void loge(String str, Throwable th) {
        Log.e(this.TAG, str, th);
    }

    public void logi(String str) {
        Log.i(this.TAG, str);
    }

    protected void terminateConnection(BluetoothGatt bluetoothGatt, int i) {
        logi("terminateConnection");
        if (this.mConnectionState != 0) {
            disconnect();
        }
        closeBluetoothGatt();
        this.mErrorState = i;
    }

    public static String toHexString(byte[] bArr) {
        StringBuilder sb = new StringBuilder();
        int length = bArr.length;
        for (int i = 0; i < length; i++) {
            sb.append(String.format("%02X ", bArr[i]));
        }
        return sb.toString();
    }
}
